import { getIconApi } from '@/api/icon'
import { useRemoteData } from '@/hooks/useRemoteData'
import { defineComponent, onMounted } from 'vue'

export default defineComponent({
  name: 'DynamicSvgIcon',
  props: {
    name: {
      type: String,
      required: true
    }
  },
  setup (props) {
    const { state, fetchData } = useRemoteData(getIconApi)
    onMounted(() => {
      fetchData(props.name)
    })
    /* render 函数 */
    return () => {
      const { data } = state
      let svgComponents: JSX.Element[] | null = null
      if (data) {
        const { components } = data
        svgComponents = components.map(component => {
          const { type, ...options } = component
          return (
            <type { ...options } />
          )
        })
      }
      return (
        <svg viewBox="0 0 1024 1024">{ svgComponents }</svg>
      )
    }
  }
})
